import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { AppThunk } from '../index'

// state变量类型
export interface publishState {
  count: number
}
export const publish = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'publish',
  // 1. 定义变量(状态数据)
  initialState: {
    count: 0
  } as publishState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    add(state, action: PayloadAction<number | undefined>) {
      state.count++
    }
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { add } = publish.actions

// 3. 异步action
export const asyncAction = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    dispatch(add())
  }
}

// 导出reducer(创建store使用)
export default publish.reducer